/**
 * 
 */
package com.hfjyz.examination.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hfjyz.examination.object.LoginInfo;

/**
 *
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private List<String> adminUrls;
	private String loginUrl;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle
	 * (javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String reqUrl = request.getRequestURI();
		if (reqUrl.contains(loginUrl)) {
			return true;
		}
		LoginInfo loginInfo = (LoginInfo) request.getSession().getAttribute(
				LoginInfo.SESSION_KEY_LOGIN_INFO);
		if (loginInfo == null) {
			request.getRequestDispatcher(loginUrl).forward(request, response);
			return false;
		} else {
			if (adminUrls != null && adminUrls.size() > 0) {
				for (String url : adminUrls) {
					if (reqUrl.contains(url)
							&& !loginInfo.hasRole(LoginInfo.ROLE_ADMIN)) {
						throw new Exception("您没有权限进行此操作！请联系系统管理员。");
					}
				}
			}
		}
		return super.preHandle(request, response, handler);
	}

	public List<String> getAdminUrls() {
		return adminUrls;
	}

	public void setAdminUrls(List<String> adminUrls) {
		this.adminUrls = adminUrls;
	}

	/**
	 * @return the loginUrl
	 */
	public String getLoginUrl() {
		return loginUrl;
	}

	/**
	 * @param loginUrl
	 *            the loginUrl to set
	 */
	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

}
